package com.xxwy.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.ExecutionException;

/**
 * @author wy
 * @date 2020/3/31 18:07
 */
public class Client {

  private static final String address = "127.0.0.1";

  public static void main(String[] args) {
    new Client().start(8000, 100);
  }

  private void start(int beginPort, int count) {
    System.out.println("client starting");
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.SO_REUSEADDR, true)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) throws Exception {

          }
        });

    int index = 0;
    int port;
    while (!Thread.interrupted()) {
      port = beginPort + index;
      try {
        ChannelFuture channelFuture = bootstrap.connect(address, port);
        channelFuture.addListener((ChannelFutureListener) future -> {
          if (!future.isSuccess()) {
            System.out.println("connect failed exit");
          }
        });
        channelFuture.get();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      } finally {
        if (++index == count) {
          index = 0;
        }
      }
    }

  }
}
